
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Mr Bao
 */
public class ImageViewNew extends Canvas implements CommandListener, Runnable {

    private UpAnh upAnh;
    private Command cmdBack = new Command("Back", Command.BACK, 2);
    private Command cmdSave = new Command("Luu", Command.OK, 2);
    private Image image;
    private Font font = Font.getDefaultFont();
    private boolean isRunning = true;

    public ImageViewNew(UpAnh upAnh, int indexImage) {
        this.upAnh = upAnh;
        upAnh.client.ViewImage(indexImage);
        addCommand(cmdBack);
        addCommand(cmdSave);
        setCommandListener(this);
        new Thread(this).start();
    }

    protected void paint(Graphics g) {
        g.setColor(0);
        g.fillRect(0, 0, getWidth(), getHeight());
        if (image != null) {
            int x = 0;
            int y = 0;
            if (image.getWidth() < getWidth()) {
                x = (getWidth() - image.getWidth()) / 2;
            }
            if (image.getHeight() < getHeight()) {
                y = (getHeight() - image.getHeight()) / 2;
            }
            g.drawImage(image, x, y, 0);
        } else {
            g.setColor(0xffffff);
            g.setFont(font);
            g.drawString("Loading...", (getWidth() - font.stringWidth("Loading...")) / 2, (getHeight() - font.getHeight()) / 2, 0);
        }
    }

    public void commandAction(Command c, Displayable d) {
        if (c == cmdBack) {
            upAnh.DisplayViewImageNameNewBack();
            isRunning = false;
        }
    }

    public void run() {
        while (isRunning) {
            if (upAnh.client.image != null) {
                image = upAnh.client.image;
                upAnh.client.image = null;
                repaint();
                break;
            }
        }
    }

    protected void keyPressed(int keyCode) {
        int key = getGameAction(keyCode);
        switch (key) {
            case RIGHT:
                upAnh.client.ViewImageNext();
                image = null;
                repaint();
                new Thread(this).start();
                break;
            case LEFT:
                upAnh.client.ViewImagePre();
                image = null;
                repaint();
                new Thread(this).start();
                break;
        }
    }
}
